{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 二叉树中的最大路径和\n",
    "\n",
    "[![Author](https://img.shields.io/badge/Author-%40mjd507-important?style=social&logo=GitHub)](https://github.com/mjd507)\n",
    "[![WeChat Channel](https://img.shields.io/badge/Wechat-Daily%20Problem-important?style=social&logo=WeChat)](https://mp.weixin.qq.com/s/8tsidlmYyVUFHA9AXxCQoQ)\n",
    "\n",
    "![Logo](img/Day84-1.png)\n",
    "\n",
    "　　给定一棵二叉树，确定一条连通2个结点的路径、使得路径中所有结点的和最大，返回该结点。路径并不一定要经过根节点。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Node:\n",
    "    def __init__(self, value: int):\n",
    "        self.value = value\n",
    "        self.left = None\n",
    "        self.right = None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def maxPathSum(root: Node) -> int:\n",
    "    def recursive(subroot: Node) -> tuple:\n",
    "        if subroot is None:\n",
    "            return (-float('Inf'), 0)\n",
    "        (leftMaxSum, leftPath) = recursive(subroot.left)\n",
    "        (rightMaxSum, rightPath) = recursive(subroot.right)\n",
    "        rootMaxSum = max(0, leftPath) + subroot.value + max(0, rightPath)\n",
    "        maxSum = max(leftMaxSum, rootMaxSum, rightMaxSum)\n",
    "        rootPath = max(leftPath, rightPath, 0) + subroot.value\n",
    "        return (maxSum, rootPath)\n",
    "\n",
    "    return recursive(root)[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```text\n",
    "(Path is labeled with brackets.)\n",
    "\n",
    "       {10}\n",
    "      /    \\\n",
    "    {2}    {10}\n",
    "    / \\       \\\n",
    " {20}  1      -25\n",
    "              / \\\n",
    "             3   4\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "42\n"
     ]
    }
   ],
   "source": [
    "root = Node(10)\n",
    "root.left = Node(2)\n",
    "root.right = Node(10)\n",
    "root.left.left = Node(20)\n",
    "root.left.right = Node(1)\n",
    "root.right.right = Node(-25)\n",
    "root.right.right.left = Node(3)\n",
    "root.right.right.right = Node(4)\n",
    "print(maxPathSum(root))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
